<?php


namespace App\Http\Admin\Controllers;

use App\Http\Admin\Controllers\Controller as Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\User;
use App\Permission;
use Illuminate\Support\Facades\Redis;
use App\Http\Authentication\UserAuthentication;
use Illuminate\Support\Facades\DB;


class UsersController  extends Controller{

    use UserAuthentication;

    /*
     * 添加用户
     * */

    public function add_user(Request $request){

        $data=$request->only('name','email','password');
        
        if(!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,10}$/u',$data['name']))  return ThrowApiExc('31001');
        if(!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/',$data['email'])) return ThrowApiExc('31002');
        if(!preg_match('/^[0-9a-z]{2,30}$/u',$data['password'])) return ThrowApiExc('31002');
//        if(!preg_match('/^[0-9\,]{1,200}$/',$data['roles']))  return ThrowApiExc('31001');
        $roles= json_decode($request->only('roles')['roles']);

        //

        $data['password']=Hash::make($data['password']);
        $data['type']=1;
        $user= User::create($data);  //新建用户


        $user = User::where('name', '=', $data['name'])->first();

        $user ->attachRoles($roles);

        return [
            'status_code'      => 200,
            'message'     =>  '添加成功',
            'data' => $user
        ];

    }

    /*
     * 修改用户
     * */


    public function update_user(Request $request,$userId){

        $data=$request->only("name","email","password");

        $roles= json_decode($request->roles);
        if(!preg_match('/^[\w\x{4e00}-\x{9fa5}]{2,10}$/u',$data['name']))  return ThrowApiExc('31001');
        if(!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/',$data['email'])) return ThrowApiExc('31002');
        // if(array_key_exists("password",$data)&&!preg_match('/^[0-9a-z]{2,30}$/u',$data['password'])) return ThrowApiExc('31101');

        if(array_key_exists("password", $data)) $data['password']=Hash::make($data['password']);

        $user= User::find($userId);
        $user = User::where('id', '=', $userId)->first();

        $user ->detachRoles($user->roles);//添加权限
        $user ->attachRoles($roles);//添加权限

        $res = $user->update($data);
        return [
            'status_code'      => 200,
            'message'     =>  '修改成功',
            'data' => $res
        ];

    }
//

    /*
     * 查找用户
     * */

    public function select_user(Request $request){

        $data = $request->only('type','phone');
        $type = $data['type'];
        if($type==1){
            $data = User::orderBy('id','DESC')->select("id","name","email","created_at","updated_at")
            ->where("type","1")
            ->paginate(10);
        }else{
            if(array_key_exists("phone",$data)){
                $data = DB::table(DB::raw("(select u.*,count(qqpu.id) as qqpucount from users as u join q_q_p_users as qqpu on qqpu.userId=u.id where qqpu.status=1 and u.type={$type} and u.phone={$data['phone']} group by u.id order by u.created_at desc) as cc
            "))->paginate(10);
            }else{
                $data = DB::table(DB::raw("(select u.*,count(qqpu.id) as qqpucount from users as u join q_q_p_users as qqpu on qqpu.userId=u.id where qqpu.status=1 and u.type={$type} group by u.id) as cc
                "))->paginate(10); 
            }
        }
        
        


        if($data){
            return [
                'status_code'      => 200,
                'message'     =>  '查询成功',
                'data' => $data
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '查询失败',
                'data' => $data
            ];
        }
        

    }


    /*
     * 查找用户的角色
     * */

    public function select_user_roles($userId){


        $user = User::find($userId);
        return $user->roles;

    }


    /*
     * 删除用户
     * */

    public function delete_user($userId){



        $data = User::find($userId)->delete();

        return [
            'status_code'      => 200,
            'message'     =>  '请求成功',
            'data' => $data
        ];
        
    }


    /*
     * 个人信息的查询
     * */
    public function select_user_info(Request $request){
        $token = getToken($request);
        $uid =Redis::get("code:".$token);
        //无用户id 返回无权限操作
        if(!$uid)  return ThrowApiExc('42334');

        $user = User::find($uid);
        $permissions=[];
        foreach ($user->roles as $k=>$v){
            foreach ($v->cachedPermissions() as $kk=>$vv){
                $permissions[]=$vv;
            }
        }
        $manageUers = new Permission;
        $permissionsAll = $manageUers->get();
        $user['permissions']=$permissions;
        $user['permissionsAll']=$permissionsAll;
        return $user;
    }

    /*
     * 手机号查询用户
     * */

    public function select_user_phone(Request $request){
        $data = $request->only("phone");

        $res = DB::table("users")->where("phone",$data['phone'])->first();
        if($res){
            return [
                'status_code'      => 200,
                'message'     =>  '查询成功',
                'data' => $res
            ];
        }else{
            return [
                'status_code'      => 200,
                'message'     =>  '查询失败',
                'data' => $res
            ];
        }
    }


}
